package demo.huodongbaoming.controller;

import demo.huodongbaoming.dto.LoginRequest;
import demo.huodongbaoming.dto.RegisterRequest;
import demo.huodongbaoming.dto.ResponseResult;
import demo.huodongbaoming.dto.UserDTO;
import demo.huodongbaoming.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseResult<UserDTO> register(@RequestBody RegisterRequest registerRequest) {
        try {
            UserDTO userDTO = userService.register(registerRequest);
            return ResponseResult.success("注册成功", userDTO);
        } catch (RuntimeException e) {
            return ResponseResult.fail(400, e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseResult<UserDTO> login(@RequestBody LoginRequest loginRequest) {
        try {
            UserDTO userDTO = userService.login(loginRequest);
            return ResponseResult.success("登录成功", userDTO);
        } catch (RuntimeException e) {
            return ResponseResult.fail(400, e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResponseResult<UserDTO> getUserById(@PathVariable Long id) {
        try {
            UserDTO userDTO = userService.getUserById(id);
            return ResponseResult.success(userDTO);
        } catch (EntityNotFoundException e) {
            return ResponseResult.fail(404, e.getMessage());
        }
    }

    @GetMapping("/username/{username}")
    public ResponseResult<UserDTO> getUserByUsername(@PathVariable String username) {
        try {
            UserDTO userDTO = userService.getUserByUsername(username);
            return ResponseResult.success(userDTO);
        } catch (EntityNotFoundException e) {
            return ResponseResult.fail(404, e.getMessage());
        }
    }
} 